package top.zhmq.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import top.zhmq.demo.domain.Authority;
import top.zhmq.demo.domain.Customer;

import java.util.List;
import java.util.stream.Collectors;

/**
 * TODO 在此处添加描述
 *
 * @author Glory
 * @classname UserDetailsService
 * @create 2021-04-25 10:38
 */

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private CustomerService customerService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 通过业务方法获取用户及权限信息
        Customer customer = customerService.getCustomer(s);
        List<Authority> authorities = customerService.getCustomerAuthority(s);
        // 对用户权限进行封装
        List<SimpleGrantedAuthority> list = authorities.stream().map(authority -> new SimpleGrantedAuthority(authority.getAuthority())).collect(Collectors.toList());
        // 返回封装的UserDetails用户详情类
        if (customer != null) {
            return new User(customer.getUsername(), customer.getPassword(), list);
        } else {
            // 如果查询的用户不存在（用户名不存在），必须抛出此异常
            throw new UsernameNotFoundException("当前用户不存在！");
        }
//        //定义权限集合，用于添加当前用户的角色
//        List<GrantedAuthority> authorities = new ArrayList<>();
//        //模拟手动封装，实际中的用户角色是需要去数据库查找
//        authorities.add(new SimpleGrantedAuthority("admin"));
//        //返回user对象，参数为用户名、密码以及对应的权限集合
//        return new User(s, new MyPasswordEncoder().encode("123456"), authorities);
    }
}
